<template>
  <div class="login-container">
    <a-card title="酒店管理系统登录" class="login-card">
      <a-form
        :model="formState"
        :rules="rules"
        @finish="handleLogin"
        layout="vertical"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState.username" placeholder="请输入用户名" />
        </a-form-item>
        
        <a-form-item label="密码" name="password">
          <a-input-password v-model:value="formState.password" placeholder="请输入密码" />
        </a-form-item>
        
        <a-form-item>
          <a-button type="primary" html-type="submit" :loading="loading" block>
            登录
          </a-button>
        </a-form-item>
        
        <div style="text-align: center;">
          <span>还没有账号？</span>
          <a-button type="link" @click="goToRegister">立即注册</a-button>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import axios from 'axios'

const router = useRouter()
const loading = ref(false)

const formState = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const handleLogin = async (values) => {
  loading.value = true
  try {
    const response = await axios.post('/api/users/login', {
      username: values.username,
      password: values.password
    })
    
    if (response.data.success) {
      // 保存token
      localStorage.setItem('token', response.data.data)
      
      // 获取用户信息
      await getUserInfo()
      
      message.success('登录成功')
      router.push('/hotel/users')
    } else {
      message.error(response.data.message || '登录失败')
    }
  } catch (error) {
    message.error(error.response?.data?.message || '登录失败')
  } finally {
    loading.value = false
  }
}

const getUserInfo = async () => {
  try {
    // 这里需要实现获取当前用户信息的接口
    // 暂时使用模拟数据
    const mockUser = {
      id: 1,
      username: formState.username,
      real_name: '管理员',
      permissions: ['user:search', 'user:create', 'user:update', 'user:delete', 'role:manage', 'role:assign']
    }
    
    localStorage.setItem('currentUser', JSON.stringify(mockUser))
    localStorage.setItem('userPermissions', JSON.stringify(mockUser.permissions))
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f0f2f5;
}

.login-card {
  width: 400px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>